以兩個示例表為例:
TableOne
---- ---------- ------------- ------------ ------------ --
| id | uid | thingone | thingtwo | thingthree | |
---- ---------- ------------- ------------ ------------ --
| 1 | 7 | 0 | 1 | 1 | |
| 2 | 8 | 1 | 1 | 0 | |
---- ---------- ------------- ------------ ------------ --
和
TableTwo
---- ---------- ------------- ------------ ------------ --
| id | oid | thingone | thingtwo | thingthree | |
---- ---------- ------------- ------------ ------------ --
| 1 | 7 | Apple | Coconut | Grape | |
| 2 | 8 | Potato | Orange | Banana | |
---- ---------- ------------- ------------ ------------ --
所以在這個例子中,用戶 ID 7 會得到 Coconut 和 Grape,而不是 Apple。Userid 8 會得到 Potato 和 Orange,但不會得到香蕉。我想以最有效的方式做到這一點,并且我意識到我可以通過一些 php 處理來做兩個單獨的查詢,但如果可行的話,我想用一個查詢來做。
我需要做的是(在單個查詢中)通過 id 從 TableOne 中獲取行,然后從 TableTwo 中選擇行,其中 theoid = TableOne 的 id 但只有在 TableOne 中為 1 而不是 0 時才從 TableTwo 中獲取相應的行.
有人可以幫忙嗎?
uj5u.com熱心網友回復:
您可以通過使用IF并逐個比較兩個表中的列來實作它。要比較 tableone 中的 tabletwo,您需要使用 JOIN,在此查詢中,我使用 LEFT JOIN。
SELECT a.id, a.`uid`,
IF(a.`thingone`=1, b.`thingone`, NULL) AS thingone,
IF(a.`thingtwo`=1, b.`thingtwo`, NULL) AS thingtwo,
IF(a.`thingthree`=1, b.`thingthree`, NULL) AS thingthree FROM tableone a
LEFT JOIN tabletwo b ON uid=oid;
查看MySQL IF() 函式以獲取更多詳細資訊。
uj5u.com熱心網友回復:
您需要制作關系表,然后使用連接查詢
uj5u.com熱心網友回復:
那這個呢:
select case when t1.thingone = 1 then t2.thingone else '' end,
case when t1.thingtwo = 1 then t2.thingtwo else '' end,
case when t1.thingthree = 1 then t2.thingthree else '' end
from TableOne t1 join TableTwo t2 on t1.uid=t2.oid
您可能需要將這三者連接起來或將它們轉換為三行,具體取決于應如何表示這三者。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/482506.html
上一篇:在條件聚合中對列值求和
