假设我有2列,大小和颜色,表的内容如下:
sizes colors
large red
large green
small green
如果我想要检索large
表中sizes
和green
表中colors
的记录,我会这样做:
$q = "SELECT * FROM tablename WHERE sizes='large' and colors='green'";
但是,如果我只想在行中同时包含large
和red
来修改green
该怎么办?
答案 0 :(得分:3)
您似乎需要检查匹配的2行。自联接可能是最简单的方法: -
SELECT *
FROM SomeTable a
INNER JOIN SomeTable b
ON a.sizes = b.sizes
WHERE a.sizes = 'large'
AND a.colors = 'red'
AND b.colors = 'green'
避免使用JOIN,但这只返回大小(你还有其他想要返回的列吗?): -
SELECT sizes, COUNT(DISTINCT colors) AS colour_count
FROM SomeTable
WHERE sizes = 'large'
AND colors IN ('red', 'green')
GROUP BY sizes
HAVING colour_count = 2