Mysql复杂where子句 [英] Mysql Complex Where Clause

查看:100
本文介绍了Mysql复杂where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很惊讶,当我尝试下面的代码在MySQL:

I really surprised when I tried below code in MySQL:

SELECT * FROM table WHERE (key='free_shipping' and value='yes') AND (key='price' and value='5')

不工作。我需要获得同时 free_shipping 为yes和 price 等于'5'的产品。如何正确创建此查询?

It doesn't work. I need to get product that is both free_shipping is 'yes' AND price equal '5' at the same time. How can I create this query properly?

表结构

content:(表1)

CONTENT_ID   TITLE  DESCRIPTION  DATE

content_fields:(表2)

FIELD_ID   CONTENT_ID    KEY_NAME    VALUE

示例

SELECT *  FROM `contents` as c LEFT JOIN `content_fields` as cf ON  c.content_id = cf.content_id WHERE c.content_id = 1 AND  cf.key_name = 'free_shipping' AND cf.value = 'yes'


推荐答案

您当前的查询是矛盾的,因为单个行永远不能匹配WHERE子句。我假设你想要这样的东西。

Your current query is contradictory as a single row can never match the WHERE clause. I assume you want something like this.

SELECT product_id
FROM table 
WHERE (key='free_shipping' and value='yes') or (key='price' and value='5')
GROUP BY product_id
HAVING COUNT(DISTINCT key) = 2

这篇关于Mysql复杂where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆