dops57958 2012-04-02 05:00 采纳率: 0%
浏览 69
已采纳

在MySQL中显示多行

I had a table like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
1    |   SAM1
3    |   SAM3
7    |   SAM7
6    |   SAM6

I need to show the results using this query

SELECT name,id FROM tblnameWHERE id IN (1,2,7,6,1)

and getting the following result

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6

My problem is this skipped last id , ie 1 . I need something like this

id   |   name 
------------------
1    |   SAM1
2    |   SAM2
7    |   SAM7
6    |   SAM6
1    |   SAM1

With out using the loop query ( like follows ) any other method for doing this ?

$ids=array(1,2,7,6,1);
$i=0;
foreach($ids as $id){

$sql=mysql_query("SELECT * FROM tblname WHERE id=$id");
// Store value to array 

}

Please help

  • 写回答

6条回答 默认 最新

  • doupi6737 2012-04-02 05:09
    关注

    The query

    SELECT name,id FROM tblname WHERE id IN (1,2,7,6);
    

    should show duplicate rows; e.g. if there are really in the table two distinct rows with the very same id, then the query will show them (since there's no DISTINCT keyword).

    Instead, if you want to create duplicate lines starting from a table containing single lines, you have to join your table with a table having repeated 1 (in your case); another way could be to use union like this:

    SELECT  name, id FROM tblname WHERE id IN (1,2,7,6)
      UNION ALL
    SELECT name, id FROM tblname WHERE id = 1;
    

    Edit

    Since your id is a primary key, it will be unique, hence the "problem" you're experiencing. If you want to allow duplicate rows on insert, remove the primary key. If you need it, consider the possible solutions suggested above.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c