我正试着从三个表中得到一个ID列表。
table_one
---------
| id | other_data |
table_two
---------
| this_id | user_id | time_qual |
table_three
---------
| this_id | second_qual |我想要一份table_one id的名单,它有以下条件:
在同一行中,1
this_id‘s user_id等于php变量$user_id和time_qual等于1。H 222h 123,但也包括符合#1和#2的ids,如果在table_two
的同一行中找不到table_one的id和php变量$user_id,则不是#3。
这是我的尝试:
SELECT tb1.id FROM table_one tb1
INNER JOIN table_two tb2
INNER JOIN table_three tb3
WHERE tb2.this_id = tb1.id
AND tb3.this_id = tb1.id
AND tb3.second_qual = 1
AND ((tb2.user_id = $user_id AND tb2.time_qual = 1)
OR ($user_id NOT IN (SELECT user_id FROM table_two)))
GROUP BY tb1.id我猜里面应该有一个UNION,tb2.this_id = tb1.id消除了我想要的#4的结果,但我不知道该怎么做。
提前感谢!
发布于 2011-10-13 04:58:07
尽我最大的能力解析您的需求,我认为这是答案。如果没有找到,请告诉我,我可以修改:
SELECT t1.id
FROM table_three t3
RIGHT JOIN table_one t1
ON t1.id=t3.this_id
LEFT JOIN table_two t2
ON t1.id=t2.this_id
WHERE (t3.this_id IS NOT NULL AND t3.second_qual=1)
AND ((t2.this_id IS NOT NULL AND t2.user_id=1 AND t2.time_qual=1)
OR t2.this_id IS NULL);https://stackoverflow.com/questions/7749324
复制相似问题