连接具有相同ID和相同列名但值不同的两个表 [英] joining two tables with same id and same name of columns but different values

查看:184
本文介绍了连接具有相同ID和相同列名但值不同的两个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力做我刚才说的话.我有两个联接表.它们通过相同的ID加入.但是有两列名称相同,我只想输出其中一列.

I am trying to do what I just said. I have two joined tables. They are joined by same id's. But There are two columns with same name and I only want to output one of the columns.

$query= "SELECT * 
        FROM users 
        INNER JOIN bookings ON users.username = bookings.personal 
        JOIN products ON bookings.productid = products.productid 
        WHERE users.id = $id 
        ";

$selectproductname = $db->prepare($selectuseremailquery);   
$selectproductname ->execute(array());  
foreach($selectproductname as $index => $rs) :

it gives me something like this table:

-id -----id----products----products------
-                                       -
-1        1      a cup     coffee cup   -
-2        2      a pen     a purple pen -  
-----------------------------------------    

我想输出咖啡杯,但是有两列具有相同的名称.如何输出?

I want to output the coffee cup, but there are two columns with same name. How can I output?

这行不通:

<td><div> <?php echo  $rs['products.productname']; ?> </div> </td>  

我必须用*选择所有内容.

And I have to select all of it with *.

推荐答案

使用SELECT *通常认为出于您要询问的确切原因,在生产软件(尤其是php)中有害.

在php中,有时将结果集加载到关联数组中.这将导致除每组重复的列名称中的一组以外的所有数据消失.

In php, sometimes the result set is loaded into an associative array. That will cause data from all but one of each set of duplicate column names to disappear.

您要使用

     SELECT products.id, 
            products.productname, 
            products.id AS product_id,
            bookings.*,
            etc., etc.

枚举结果集中所需的列. (请注意,我正在猜测您的列名).

to enumerate the columns you need in your result set. (Notice that I'm guessing at your column names).

我知道您的问题说您必须使用SELECT *.我怀疑那是真的.如果是这样,那可能是一个不知道他们在说什么的人强加的要求. (愚蠢的教授把戏浮现在脑海.)

I know your question says you have to use SELECT *. I doubt that's true. If so it's a likely to be requirement imposed by somebody who doesn't know what they're talking about. (Stupid professor tricks come to mind.)

如果必须使用SELECT *,则需要使用结果集元数据来检查每一列的元数据,并找出需要提取的列. getColumnMeta() 可以做到这一点.

If you do have to use SELECT *, you'll need to use the result set metadata to examine each column's metadata and figure out which columns you need to extract. getColumnMeta() does that.

这篇关于连接具有相同ID和相同列名但值不同的两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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