简体   繁体   English

连接具有相同ID和相同列名但值不同的两个表

[英]joining two tables with same id and same name of columns but different values

I am trying to do what I just said. 我正在努力做我刚才说的话。 I have two joined tables. 我有两个联接表。 They are joined by same id's. 它们由相同的ID组成。 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? 如何输出?

This didn't work: 这不起作用:

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

And I have to select all of it with *. 我必须选择所有带有*的内容。

Using SELECT * is generally considered harmful in production software, especially in php, for the precise reason you're asking about. 由于您要询问的确切原因,在生产软件中,尤其是在php中,使用SELECT *通常被认为是有害的

In php, sometimes the result set is loaded into an associative array. 在php中,有时将结果集加载到关联数组中。 That will cause data from all but one of each set of duplicate column names to disappear. 这将导致除了每组重复的列名称中的一组以外的所有数据消失。

You want to use 你想用

     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). (请注意,我正在猜测您的列名)。

I know your question says you have to use SELECT * . 我知道您的问题说您必须使用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.) (愚蠢的教授把戏浮现在脑海。)

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. 如果必须使用SELECT * ,则需要使用结果集元数据来检查每一列的元数据,并找出需要提取的列。 getColumnMeta() does that. getColumnMeta()做到这一点。

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

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