表1 - > id,名称
表2 - > id,name,text_value,table1_id,table3_id
表3 - > id,name
SELECT * FROM `table1`
LEFT OUTER JOIN table2 ON table1.id = table2.table1_id
WHERE
(
(table2.table3_id = '7' AND table2.name like ('%test%'))
)
AND
(
table2.table3_id = '1' and table2.text_value like ('%fast update%'))
)
GROUP BY table1.id
ORDER BY table1.id desc
答案 0 :(得分:1)
简短的回答,是的。
更长的答案,重新阅读你的问题几次以下将有效,但不会是世界上最有效的查询,我强烈建议你重新审视你想要完成的事情和表格重组会是一个好主意。
我选择了INNER JOIN,因为您只对符合这两个条件的行感兴趣,因此NULL行不重要。 HAVING子句确保仅输出与两者匹配的行,而在ON子句中具有table2限制有助于限制性能影响。
SELECT
table1.*,
COUNT(DISTINCT(table3.id)) AS numberOfMatches
FROM table1
INNER JOIN table2
ON table2.table1_id = table1.id
AND (
(table2.table3_id = 7 AND table2.name LIKE '%test%')
OR
(table2.table3_id = 1 AND table2.text_value LIKE '%fast update%')
)
INNER JOIN table3
ON table3.id = table2.table3_id
GROUP BY table1.id
HAVING numberOfMatches = 2
ORDER BY table1.id DESC
答案 1 :(得分:1)
是的,但您需要两个连接才能这样做:
t2
。AND
更改为LEFT OUTER JOIN table2 AS t2 ON
。table2
更改为t2
。GROUP BY
时,您指定的所有列都必须位于GROUP BY
子句或聚合中。由于您没有这样做,并且不清楚为什么您尝试使用GROUP BY
,我正在删除GROUP BY
条款。还有其他一些变化。请参阅下面的最终查询:
SELECT
table1.id
FROM
table1
LEFT OUTER JOIN
table2
ON table1.id = table2.table1_id
LEFT OUTER JOIN
table2 t2
ON table1.id = t2.table1_id
WHERE
table2.table3_id = '7'
and
table2.name like '%test%'
AND
t2.table3_id = '1'
and
t2.text_value like '%fast update%'
ORDER BY
table1.id DESC
答案 2 :(得分:0)
SELECT *
FROM `table1` a LEFT OUTER JOIN table2 b ON a.id = b.table1_id
WHERE
(
b.table3_id = '7' AND b.name like '%test%'
)
AND
(
b.table3_id = '1' and b.text_value like '%fast update%'
)
GROUP BY a.id
ORDER BY a.id desc