简体   繁体   English

SQL查询:我需要两个查询还是可以使用嵌套子查询

[英]SQL Query: do I need two queries or can I use a nested subquery

This question may have been asked before but I don't really know what verbiage to search with. 之前可能已经问过这个问题,但是我真的不知道该用哪个词。

I have a mysql DB that has a table with 3 columns [ID, fieldName and fieldValue] that is used to describe attributes of objects in another table. 我有一个MySQL数据库,该数据库具有一个包含3列[ID,fieldName和fieldValue]的表,该表用于描述另一个表中对象的属性。 The ID field stores the foreign key of object in the other table and the fieldName and fieldValue store things like title, description, file size and summary. ID字段将对象的外键存储在另一个表中,fieldName和fieldValue存储诸如标题,描述,文件大小和摘要之类的内容。

I am trying to write a query that returns rows where a fieldName and fieldValue pair match known values and the returned row ID has a another distinct fieldValue in another row. 我正在尝试编写一个查询,该查询返回的字段中fieldName和fieldValue对匹配已知值,并且返回的行ID在另一行中具有另一个不同的fieldValue。 Right now I am accomplishing it with two queries and an if statement. 现在,我通过两个查询和一个if语句来完成它。 Here is the sudo code: 这是sudo代码:

$result = SELECT * FROM table_a WHERE fieldName = 'title' and fieldValue = 'someTitle'
$test = SELECT * FROM table_a WHERE fieldValue = 'someValue' and id = '{$result['id']}'
if ($test) {
  /* Result Found */
}

You can self-join the table: 您可以自行加入表格:

SELECT * FROM table_a AS s1 
JOIN table_a AS s2 USING (id)
WHERE
    s1.fieldName = 'Title' AND s1.fieldValue = 'someTitle'
    AND s2.fieldValue = 'someValue'

What you said translated in sql would be: 您说的用sql翻译的内容是:

SELECT b.* 
FROM table_a a
INNER JOIN table_a b ON a.id = b.id
WHERE a.fieldName = 'title'
  AND a.fieldValue = 'someTitle'
  AND a.fieldValue <> b.fieldValue

This gets you the rows in table_a that have the same id as the row with you predefined values, but with a different fieldValue. 这使您获得table_a中具有与预定义值相同的ID的行,但具有不同的fieldValue。 This assumes that id is not the primary key, otherwise there will not be another row with the same id, but it looks in your question that this isn't the case. 假设id不是主键,否则将不会有另一个具有相同id的行,但是在您的问题中看起来并非如此。 (If you want to check for a specific value you can do: AND b.fieldValue = 'someValue' in the last line) (如果要检查特定值,可以执行以下操作: AND b.fieldValue = 'someValue'在最后一行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM