I've got a query to my MySQL database returning four fields of information from a MySQL table (information), which I then encode for JSON using PHP's json_encode() function. Two of the fields it returns are "staffMember" and "lineManager", which return integers that relate to the ID of that person in a (separate) users table.
My query returns the following (in table format):
id is 1
staffMember is 14
lineManager is 12
description is this is a description
etc.. for all the rows.
14 (in the case of the above for example) refers to a row in the users table that would be something like:
id is 14
firstname is dave
secondname is jones
My question is therefore, how can I get the JSON part of the query to return "dave jones" instead of 14? As the info isn't held in the same table in MySQL.
Use LEFT JOIN in your database request like
SELECT a.id, CONCAT(b.firstname, ' ', b.secondname) AS staffMember, a.lineManager, a.description
FROM a
LEFT JOIN b ON (a.staffMember = b.id)
where a and b - your table names
As the commenters mentioned, you will definitely want to add the firstname and lastname fields to your SQL result set. You can do this by altering your query to JOIN to the table that houses your firstname and lastname data. The "ON" clause of your join would be the id common to both tables. An example would be:
SELECT * FROM yourdb.table1 T1 LEFT JOIN yourdb.table2 T2 ON T1.staffMember = T2.id;
Related
I have two different tables. One is person and the other one is Cardholder. Both of these tables have one row with the similar name and same value and its called personId. What I am trying to do is compare the row personId on the person table to personId on the Cardholder table and print only rows that match the value of personId on both tables. How would I write in PHP to do such task? I tried few things but failed to do what I intend.
The sql query would look something like this :
SELECT P.* FROM person P
INNER JOIN Cardholder C ON C.personId=P.personId
this would only select the fields from the table person that has a match on personId in the Cardholder table.
You will need code like this one
MySQL Code: -
("SELECT Cardholder.personId, person.personId FROM Cardholder INNER JOIN person ON Cardholder.personId = person.personId");
PHP Code: -
if (count($SQLstatment) > 0) {Exist} else {Not}
I have 2 tables A & B
Table A
ID NAME
1 John
2 Jack
3 Mark
Table B
ID phone UserID
s1 4586 1
s2 6996 1
s3 9654 2
they are one to many relation (John has 2 phone on Table 2)
my sql query
$sql = 'SELECT *
FROM
A
Join
B
ON
B.USER_ID = A.ID
WHERE
A.ID=:ID';
my PHP
foreach($vars['GROUPS'] as $row) {
<tr><th>Name</th><td><?=$row['Name']?></td></tr>
<tr><th>phone</th><td><?=$row['phone']?></td></tr>
}
I want to show the phones number for this user John name then show all his details from table 2 . as it now loop for me
You have 2 options:
Use group_concat() function in sql to concatenate all telephone numbers a user has into a single string and use pretty much the same loop in php as you use now.
select a.id, a.name, group_concat(b.phone) as phone
from a inner join b on a.id=b.user_id
group by a.id, a.name
Leave your current sql query intact, but change the php loop displaying the table. In this case only print out a name with all the corresponding phone numbers after looping through all the records returned from the query. Just concatenate all phone numbers in the loop.
I do not know if I understand your question right. From your query you get two rows for the user John, one is "1-John-s1-4586-1" and the other is "1-John-s2-6996-1", right? And you want just one row for that user containing both his phone numbers? Then you could use GROUP_CONCAT:
SELECT A.*, GROUP_CONCAT(b.phone) FROM
A INNER JOIN B ON A.id = B.UserID
WHERE A.ID=:ID
GROUP BY A.id
See the MySQL documentation for more options of the GROUP_CONCAT function: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
For example, you could use ordering or a custom separator.
In PHP you could use explode() if you want to iterate over the phone numbers.
I seem to be a little stumped... I'm trying to get data from three tables, but they're not all inter-related -- one table relates to each of the other two.
Exams_taken
ID
exam_id
user_id
Exams_available
ID
exam_name
Users
ID
user_name
I want to create an output where I have the exam_id, exam_name, and user_name.
I thought I could figure out how to do this as a single query, but I'm lost. Is it possible? Or do I need to do a query on 'Exams_available' and then a loop with a second query to JOIN 'Exams_taken' and 'Users'?
Thanks,
Scott
If you need an output that contains exam_id, exam_name and user_name I can suppose that you need the Exams taken, so why not just query like this:
SELECT exam_id, E.exam_name, U.user_name FROM Exams_taken as ET
INNER JOIN Exams_available as E on ET.exam_id = E.exam_id
INNER JOIN Users as U on ET.user_id = U.user_id
I need to report the number of records that match each of several criteria. For example, how many customers live in each state. I know I can accomplish this through a series of MySQL SELECT statements, but that seems cumbersome and produces a ton of (unnecessary?) MySQL calls.
Can you tell me a better method to use? Can I query the database with one SELECT statement and then use PHP to filter the results to variables?
I'd suggest creating a view for this task just to hide the complexity of the query. Also, in the event that your table schema changes, it is likely that you are still going to want to retrieve this same information from the database. You'd be able to change the view in one place, instead of having to change the queries in, possibly, multiple places to satisfy your schema changes.
I'll just show you the queries, though, since you'd need to know how to do that to create a view anyways.
Sticking with your example of customers living in each state, let's pretend you also want statistics on how many customers share the same last name.
I've setup a mock structure of what your database might be like at this SqlFiddle.
Customers with Same LastName
The following query might be used to get the number of customers with the same last name:
SELECT
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName;
Customers in Same State
Similarly, the customers in the same state might be retrieved with a query as follows:
SELECT
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State;
Getting Your Desired Format
The format that you want is an aggregation of these two queries. You want both returned as a single result set. So, let's workout a schema for the returned table:
ResultType - This will hold a value that corresponds to the type of result. i.e. "State"
Value - This will hold the value of the aggregated column. i.e. "Florida"
Count - This will hold the total number of records that match the aggregated column.
So, now that we have a format, let's create a query that uses our two queries from above, and puts them into this format.
First, I add a new field to each of the above queries: ResultType
For example:
"LastName" AS "ResultType"
Now, I combine my queries into a single query using the UNION ALL statement:
SELECT * FROM (
/* LastName query */
SELECT
"LastName" AS "ResultType",
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName
UNION ALL
/* States query */
SELECT
"State" AS "ResultType",
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State
) AS A
In my SqlFiddle above, this produces an output like:
RESULTTYPE VALUE COUNT
=================================
LastName Jetson 1
LastName Johnson 2
LastName Milton 1
State Florida 2
State Georgia 1
State Utah 1
As you can see, this could get quite complex, so you might consider looking into placing this into a view. Then, you'd be able to query your view, as if it was the table above (ResultType, Value, and Count). That would also allow you to filter on it.
create select query make number of aliens of table and make your related columns aliens which is you want to use.
lest see sample example
SELECT a.id AS id
FROM Table1 AS a
WHERE ...
UNION ALL
SELECT b.name AS name
FROM Table2 AS b
WHERE ...
ORDER BY (a or b) ...
I have two table in the same database: hlstats_Events_Connects and hlstats_PlayerUniqueIds.
In the hlstats_Events_Connects I have a value I wish to get, however the ID it's related to I need to get from the data in another table, using the "uniqueId" that I have. Example:
**hlstats_Events_Connects**
playerId eventTime
----------------------
8 2013-04-05 05:44:14
**hlstats_PlayerUniqueIds**
playerId uniqueId
---------------------
8 0:0:84901
So I have the "uniqueId" as a variable, and I want to say, get the playerId of the persons uniqueId, then get the eventTime from what the playerId is. Currently I have something along the lines of the below, but can't figure out the Where clause.
SELECT c.eventTime, c.playerId, u.uniqueId, u.playerId
FROM c.hlstats_Events_Connects, u.hlstats_PlayerUniqueIds
WHERE ...?
Cheers
Looks like you are just missing the JOIN. You will join the tables on the playerId column:
SELECT c.eventTime, c.playerId, u.uniqueId, u.playerId
FROM c.hlstats_Events_Connects c
INNER JOIN u.hlstats_PlayerUniqueIds u
ON c.playerId = u.playerId
Note, I updated the query to use ANSI JOIN syntax, in this case an INNER JOIN. This is standard SQL syntax, instead of commas between the tables and the join in the WHERE
Use JOIN like this
SELECT c.eventTime, c.playerId, u.uniqueId, u.playerId
FROM c.hlstats_Events_Connects, u.hlstats_PlayerUniqueIds
WHERE c.playerId = u.playerId
You don't need to add prefixes to table names, instead those should be specified after table name, and also you can just join on playerId column (if those are large tables, I'd suggest adding an index to those columns.)
SELECT
c.eventTime, c.playerId, u.uniqueId, u.playerId
FROM
hlstats_Events_Connects c,
hlstats_PlayerUniqueIds u
WHERE
u.uniqueId = "0:0:84901" and
u.playerId = c.playerId