duanfei1268 2011-07-19 22:27
浏览 28
已采纳

如何根据SQL / php中另一列的多个值从列中选择单个值

The database is not mine. The structure is

fid| uid | value
 3 |  3  | spain
 3 |  5  | France
 2 |  3  | 45
 6 |  3  | male
 6 |  5  | female
 2 |  5  | 32

The field ID is primary key in another table, I'd like to forget about. Im trying to find all uid that have values 'spain', 'male'

I have the following working.

SELECT uid 
FROM DATABASE
WHERE value IN ('spain', 'male') GROUP BY uid HAVING COUNT(*) >= 2

The catch is as follows.. How would I select male, spain with value in range of 20-30 (that is males born in spain aged between 20-30?

Thanks a ton!!

  • 写回答

5条回答 默认 最新

  • doormen2014 2011-07-19 22:37
    关注

    You have a really messed up table. You are mixing unrelated things in value.

    Try:

    SELECT uid
    FROM DATABASE a JOIN
      DATABASE b USING (uid)
    WHERE a.value IN ('spain', 'male')
      AND b.value >= 20
      AND b.value <= 30
    GROUP BY uid
    HAVING COUNT(*) >= 2
    

    Note that I am comparing a string and an integer. You will need to test to see how well that works.

    Also, I just put spain and male together, but perhaps they are really unrelated?

    Does fid determine the type of value?

    Try:

    SELECT uid
    FROM DATABASE country
    JOIN DATABASE gender USING (uid)
    JOIN DATABASE age USING (uid)
    WHERE
      country.fid = 3 AND
      gender.fid = 6 AND
      age.fid = 2 AND
      county.value = 'spain' AND
      gender.value = 'male' AND
      age.value >= 20
      age.value <= 30
    GROUP BY uid
    HAVING COUNT(*) >= 2
    

    This code should work more reliably.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败