How to display values from two Mysql tables with similar columns. - php

Good day, I selected two MySQL tables- tcomment and members, but these two tables have similar fields called 'id' and now, I want to select the id of the 'tcomment' table but instead, the id of 'members' table shows up. How do I do this? This is the code below.
<?php
$comment= "SELECT c.*, m.* FROM tcomment c JOIN members m ON c.poster = m.id WHERE comment_id = :id";
foreach ($db->query($comment, array('id' => $_GET['id'])) AS $tresult){
echo "{$tresult['id']}";
}
?>

You could use aliases on the SQL query;
Sample Code
$comment= "SELECT c.*, c.id as comment_id, m.*, m.id as member_id FROM tcomment c JOIN members m ON c.poster = m.id WHERE comment_id = :id";

As #u_mulder said, apply aliases
$comment =<<<ccc
SELECT c.id AS 'idWanted', c.*, m.*
FROM tcomment c JOIN members m ON c.poster = m.id
WHERE comment_id = :id
ccc;
foreach ($db->query($comment, array('id' => $_GET['id'])) AS $tresult){
echo "{$tresult['idWanted']}";
}

Related

problem relating two tables for get same id mysql

I have problems to relate the columns of two tables
this is my table1 structure
where I want to relate the identify column to the id of table 2
this is my table2 structure
this is my query
$id = (!empty($_GET['id']) ? $_GET['id'] : 0);
$example1 = (!empty($_REQUEST['example1']) ? $_REQUEST['example1'] : '');
$example2 = (!empty($_REQUEST['example2']) ? $_REQUEST['example2'] : '');
$consult = "SELECT a.id, a.user, a.date, a.action
FROM table1 a
INNER JOIN table2 b on b.idwork = $id
WHERE module = 'Activity ".$idexample1."|".$idexample2."' AND identifier = $id ORDER BY id DESC ";
I get this after run my query
SELECT a.id, a.user, a.date, a.action
FROM table1 a
INNER JOIN table2 b on b.id = 244
WHERE module = 'activity 1|98' AND identificador = 244 ORDER BY id DESC
what I try is to relate and make is that $id be the same identifier number
The join should be based ON the equality of the columns b.id and a.identifier:
SELECT a.id, a.user, a.date, a.action
FROM table1 a INNER JOIN table2 b
ON b.id = a.identifier
WHERE a.module = 'activity 1|98' AND b.idwork = 244
ORDER BY a.identifier DESC
I used also the WHERE clause from your code and changed the column names to the ones of your sample data.

Moving the workload from PHP to MySQL

I currently have two queries that are executed in order. The first query pulls a few rows from a database and the 2nd query is executed using one value from those rows. I am only interested in the rows from the 1st query where I know the 2nd query is going to return a value higher than 0. I could potentially have thousands of rows in my first table, so I rather do the filtering in MySQL and not in PHP, I would assume it is faster.
The first query is as following
SELECT
*
FROM
wp_invoices
WHERE
deleted = 0
The 2nd query is as following:
SELECT COUNT(*) FROM wp_users A
INNER JOIN wp_usermeta B ON (A.ID = B.user_id)
LEFT JOIN wp_invoices_records C ON (A.ID = C.uid
AND C.invoice_id = %d
AND C.status != 100)
WHERE (B.meta_key = 'wp_capabilities' AND CAST(B.meta_value AS CHAR) LIKE '%%\"subscriber\"%%')
AND (C.uid IS NOT NULL)
Both queries work separately, this is not the problem. Currently, the %d in the 2nd query is replaced by PHP, which inserts the wp_invoices.id value for each row.
Ideally, I would like a query that returns only the rows from wp_invoices, where the 2nd query would return a value higher than 0. At this point I am not interested in the rows of the 2nd query, only the amount of rows found.
My table structures are as following: http://sqlfiddle.com/#!9/466cb
This is what I do in PHP, currently, to handle all this. Please keep in mind that this code was written to clarify this post, I am using deprecated MySQL functions because I don't write PHP that often anymore and haven't really looked into mysqli and I haven't checked if this code actually runs. It should give you a better indication of what I am currently doing.
<?php
/* Example code. I am not using mysql_ functions in my own solution, I just
know these functions by heart. Assume a database connection is already
established */
/* Refer to this as QUERY 1 */
$result = mysql_query("SELECT * FROM wp_invoices WHERE deleted = 0");
/* Loop over all invoices (this is not an invoice 'record'. These are
the invoice definitions, not the actual instances that people received */
while($row = mysql_fetch_assoc($result)) {
/* Refer to this as QUERY 2 */
$count_result = mysql_query(sprintf("
SELECT
COUNT(*) AS count
FROM wp_users A
INNER JOIN wp_usermeta B ON (A.ID = B.user_id)
LEFT JOIN wp_invoices_records C ON (A.ID = C.uid
AND C.invoice_id = %d
AND C.status != 100)
WHERE (B.meta_key = 'wp_capabilities'
AND CAST(B.meta_value AS CHAR) LIKE '%%\"subscriber\"%%')
AND (C.uid IS NOT NULL)", $row['id']));
if(mysql_result($count_result, 0) > 0) {
/* Here I would pull all data I would need for this invoice. $row
contains all the information about the invoice, $invoice_record
will contain all the information for this particular user about
this invoice*/
$invoice_records = mysql_query(sprintf("
SELECT
A.ID AS id,
A.display_name,
C.id AS received,
DATE_FORMAT(C.received_on, '%%d-%%m-%%Y') AS received_on,
C.status,
A.user_email,
C.price,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'first_name'
AND user_id = A.ID) AS first_name,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'tssnvgsl'
AND user_id = A.ID) AS insertion,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'last_name'
AND user_id = A.ID) AS last_name
FROM wp_users A
INNER JOIN wp_usermeta B ON (A.ID = B.user_id)
LEFT JOIN wp_invoices_records C ON (A.ID = C.uid
AND C.invoice_id = %d
AND C.status != 100)
WHERE (B.meta_key = 'wp_capabilities'
AND CAST(B.meta_value AS CHAR) LIKE '%%\"subscriber\"%%')
AND (C.uid IS NOT NULL)", $row['id']));
while($invoice_record = mysql_fetch_assoc($invoice_records)) {
/* Perform logic to see if this person should receive a reminder */
}
}
}
?>
What I attempt to achieve, though:
<?php
$result = mysql_query(/* here a query that pulls all rows from QUERY 1
where QUERY 2 would have returned a count higher than 2 */);
while($row = mysql_fetch_assoc($result)) {
/* Now here I should be 100% sure that every $row has at least one
"pending" invoice record, that has not yet been paid and has a
status of < 100 */
}
?>
Alright. I have been racking my brain staring at your process and I think it is starting to make sense. If I am not mistaken you should be able to eliminate both query1 and query2 and move the logic into the LEFT JOIN of your third query like such.
SELECT
A.ID AS id,
A.display_name,
C.id AS received,
DATE_FORMAT(C.received_on, '%%d-%%m-%%Y') AS received_on,
C.status,
A.user_email,
C.price,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'first_name'
AND user_id = A.ID) AS first_name,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'tssnvgsl'
AND user_id = A.ID) AS insertion,
(SELECT meta_value FROM wp_usermeta WHERE meta_key = 'last_name'
AND user_id = A.ID) AS last_name
FROM wp_users A
INNER JOIN wp_usermeta B ON (A.ID = B.user_id)
LEFT JOIN wp_invoices_records C ON (A.ID = C.uid
AND C.invoice_id IN (SELECT id FROM wp_invoices WHERE deleted = 0)
AND C.status != 100)
WHERE (B.meta_key = 'wp_capabilities'
AND CAST(B.meta_value AS CHAR) LIKE '%%\"subscriber\"%%')
AND (C.uid IS NOT NULL)"
This query, instead of having to be ran every time for every record and the $row['id'] added via php within your LEFT JOIN I am using MySQL IN functionality with a subselect. This gives you the ability to join only on records from wp_invoices which where deleted.

How to display users from two MySQL tables

I have two mysql tables-members and addclique. Members table contains the details of all users while addclique table is 'friends' table with two columns-adder_id, which contains id of the user that sent a friend request and clique_id, contains the id of user that accepted the friend request.
Please am trying to select the friends of a particular user but am finding hard getting the details (photo, name, etc) of the friends from the members table because I don't know at which point to join members table to the addclique table.
$sql = "SELECT i.*, m.* FROM addclique i JOIN members m ON m.id = ******** WHERE adder_id = :id OR clique_id = :id";
$result= $db->query($sql, array('id' => $_SESSION['id']);
The query below will select all members that a particular person has added plus all members that have added the same person.
select m.* from members m
join addclique a on m.id = a.adder_id
where a.clique_id = :id
union
select m.* from members m
join addclique a on m.id = a.clique_id
where a.adder_id = :id
If I'm understanding your question correctly, you need to join on m.id = a.adder_id or m.id = a.clique_id. You can do this with in:
set #id := 4;
select *
from members m
join addclique a on m.id in (a.adder_id, a.clique_id)
where #id in (a.adder_id, a.clique_id)
and m.id != #id
SQL Fiddle Demo

getting data from four tables with tight WHERE clause

i need help getting data from different tables and insert into other different table Here are the Queries
"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"
"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
// $parentID need to be matched from above query parentID,
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query
"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query
Last 2 queries are from same table but using different where clause
i used different inner join left join from solutions posted here but non of these worked for me stuck since last 2 weeks please help
PS data from all above Queries will be inserted to a single table i need these to be combined so i can have them all in one place
If you want to perform the operation in same query use 'OR'
"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID OR aBUserID = $topicaBUserID";
Please try this
SELECT userName from users where aBUserID IN(SELECT aBUserID FROM comments WHERE status = 'APPROVED')
Couldn't test it but Maybe this is what you are looking for.
SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID,
t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
u.userName
FROM
comments c
left outer join topic t on t.topicID = c.parentID
left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
c.status = 'APPROVED' and t.status = 'APPROVED';
try this:
SELECT
comment.[commentID],
comment.[date],
comment.[comment],
comment.[subject],
comment.[parentID],
comment.[aBUserID],
commentuser.[userName],
topic.[topicID],
topic.[subForumID],
topic.[aBUserID],
topic.[lastPostID],
topic.[views],
topic.[replies],
topic.[startDate],
topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
SELECT
t.[topicID],
t.[subForumID],
t.[aBUserID],
t.[lastPostID],
t.[views],
t.[replies],
t.[startDate],
u2.[userName] --user from users table joined to topics table
FROM topic t
LEFT OUTER JOIN users u
ON u.aBUserID = t.[aBUserID]
WHERE t.[status] = 'APPROVED'
) topic
ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'

mysql inner join query where id is obtained from $_GET['id']

I have two tables firm and contactdetails. I am trying to get the the firm name from firm and certain contact details from contactdetails. I am using $id =$_GET['id']; to get the id . In contactdetails i have fk_firm_id which is my foreign key. I am not sure how to use the inner join query. I am trying the following query:
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1`
FROM contactdetails JOIN firm ON contactdetails.fk_firm_id='$id'";
echo $sql;
$result = mysql_query($sql);
but i am not getting the correct firm. Can anyone help me with this query, please.
You should use like this JOIN firm ON contactdetails.fk_firm_id = firm.id
$sql=" SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1`
FROM contactdetails
JOIN firm ON contactdetails.fk_firm_id = firm.id
WHERE contactdetails.fk_firm_id = '$id'
";
$result = mysql_query($sql);
This is assuming that your firm table has a primary key called id
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1` FROM contactdetails JOIN firm ON `contactdetails`.`fk_firm_id`=`firm`.`id`
WHERE `firm`.`id` = '$id'";
echo $sql;
$result = mysql_query($sql);
There is a mistake about JOIN and WHERE statements:
$sql = "SELECT
f.name,
c.address_physical_line_1,
c.fax_1,
c.phone_1
FROM
contactdetails c JOIN firm f ON c.fk_firm_id= f.id
WHERE c.id = '$id'";
$sql="SELECT firm.`name` ,`address_physical_line_1` , `fax_1` , `phone_1` FROM
contactdetails JOIN firm ON contactdetails.fk_firm_id=firm.id where
contactdetails.fk_firm_id='$id'";
you should join on a firm's field such as firm.id
syntax: FROM table1 LEFT JOIN table2 ON table1.field1 compopr
table2.field2 compopr is : "=","<",">","<=",">=","<>"
You are missing the WHERE clause that limits the result set to only the firm you're interested in; now you're getting all firms joined with a single contact details record.
.. where firm.id=$id
For new applications, please use a database API that has prepared statements, like mysqli or pdo.
Use the following query for inner join
$sql="SELECT firm.name ,address_physical_line_1 , fax_1 , phone_1 FROM
contactctdetails INNER JOIN firm ON contactdetails.fk_firm_id=$id";

Categories