我有这个mysql查询,实际上Stackoverflow上有人给了我。 (它选择在pic1,pic2和pic3列中一起找到的两个最常见的id)。
它工作得很好,但现在我想在查询中添加一个WHERE子句,以便只选择我的表中存在特定ID的行。即。
WHERE pic1 =$loggedin_user OR pic2 = $loggedin_user OR pic3= $loggedin_user
谁能告诉我该条款在下面的查询中的位置?
查询
SELECT LEAST(p1, p2) AS p1, GREATEST(p1,p2) AS p2
FROM (
SELECT pic1 AS p1, pic2 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic2 IS NOT NULL
UNION ALL
SELECT pic1 AS p1, pic3 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic3 IS NOT NULL
UNION ALL
SELECT pic2 AS p1, pic3 AS p2
FROM mytable WHERE pic3 IS NOT NULL AND pic2 IS NOT NULL
) s
GROUP BY LEAST(p1, p2), GREATEST(p1,p2)
ORDER BY COUNT(*) DESC
LIMIT 1
答案 0 :(得分:0)
(不详细检查查询),它会在这里:
SELECT LEAST(p1, p2) AS p1, GREATEST(p1,p2) AS p2
FROM (
SELECT pic1 AS p1, pic2 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic2 IS NOT NULL
UNION ALL
SELECT pic1 AS p1, pic3 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic3 IS NOT NULL
UNION ALL
SELECT pic2 AS p1, pic3 AS p2
FROM mytable WHERE pic3 IS NOT NULL AND pic2 IS NOT NULL
) s
WHERE pic1 =$loggedin_user OR pic2 = $loggedin_user OR pic3= $loggedin_user
GROUP BY LEAST(p1, p2), GREATEST(p1,p2)
ORDER BY COUNT(*) DESC
LIMIT 1
中的SELECT定义
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]