douguan3470 2015-04-13 06:30
浏览 74
已采纳

在Mysql Query中添加Where子句?

I have this mysql query which in fact someone on Stackoverflow gave me. (It selects the two most frequent id's found together in the columns pic1,pic2 and pic3). It works great but now I want to add a WHERE clause to the query so that only rows in my table where a particular ID is present are selected. ie. WHERE pic1 =$loggedin_user OR pic2 = $loggedin_user OR pic3= $loggedin_user Can anyone tell me where the clause would go within the query below?

The Query

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
  • 写回答

1条回答 默认 最新

  • dongxi8993 2015-04-13 07:52
    关注

    (Without checking the query in detail), it would go here:

    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
    

    This is the SELECT definition from the MySQL documentation

    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]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Docker容器里已经安装了ssh,但打包迁移到新机器一直容器一直提示unrecognized service。
  • ¥15 综合布线实例设计,就好看好看不恐怖可好滤镜好聚
  • ¥15 使用moviepy库视频合并时出错
  • ¥30 FLUENT液固传质UDF
  • ¥15 怎么看梯度直方图以,怎么判断梯度消失/爆炸,怎么解决
  • ¥15 aspnetdll文件访问拒绝
  • ¥15 wpf中在模版中寻找元素
  • ¥15 MFC平台生成指定圆
  • ¥15 jmeter出现403
  • ¥500 求华为P30PRO手机硬盘数据恢复