dongwuwei0718 2013-12-13 21:39
浏览 251
已采纳

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

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. 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.

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. Right now I am accomplishing it with two queries and an if statement. Here is the sudo code:

$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 */
}
  • 写回答

2条回答 默认 最新

  • douwei1944 2013-12-13 21:49
    关注

    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'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据