I've got 2 tables, a join, a SELECT *. Both tables contain the field id, but I need to explicitly access one in this way:
$query = "SELECT * FROM #__docman as d JOIN #__users u ON d.dmmantainedby = u.id WHERE d.catid = 5 ORDER BY d.id ASC";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row) {
echo $row->id ;
}
I tried
echo $row->d.id;
That didn't work..I know I could technically change my SELECT to call for the id's and use aliases but, there are a lot of fields I am fetching, hence the *. Is there another way?
You'll have to use aliases, the query stays short if you duplicate the data:
"SELECT *, d.id as did, u.id as uid FROM #__docman as d JOIN #__users u ON d.dmmantainedby = u.id WHERE d.catid = 5 ORDER BY d.id ASC"
And then:
$row->did
$row->uid
SELECT *, d.id AS id_alias FROM ... ? This will select duplicate columns but will still be pretty short query.
Related
I have a general question regarding the assigning of sql results to a arrays.
What should I do when I want to assign some results to an array and when I am joining two or more tables and some columns got the same name:
Example:
$sqlExample = "select u.first_name, o.first_name from tbl_user u join tbl_owner o on u.user_id = o.user_id where u.user_id = $user_id;";
...
$userFirstName[$var] = $result['first_name'];
$ownerFirstName[$var] =
I know, that this is not a great example, but I hope that you are understanding my question..
I thought I could use something like the table prefix for the results, but it didn't worked.
-- Just an example not the code I am using/
Alias your columns in the results:
select u.first_name as user_first_name, o.first_name as owner_first_name from ...
Then use those aliases in your code:
$userFirstName[$var] = $result['user_first_name'];
$ownerFirstName[$var] = $result['owner_first_name'];
$sqlExample = "SELECT
u.first_name AS user_first_name,
o.first_name AS owner_first_name
FROM tbl_user u
JOIN tbl_owner o ON u.user_id = o.user_id
WHERE u.user_id = $user_id";
$result['user_first_name'];
$result['owner_first_name'];
I have tables:
trips: Trip_Num, Trip_Type,Trip_Geographic, etc.
travelers_trips_history: Username, Trip_Num, Trip_Type, Trip_Season, etc.
In table 2 there are trips the user did and I need to know what is the most common Trip_Geographic that in his trip's history (The Trip_Geographic need to be known by table 1 - trips by his Trip_Num).
I am doing a project in PHP and need to do a SQL query for a specific user (by his username) - need to receive a table that the columns are: 1. Trip_Geographic, count of the occurrence the Trip_Geographic is in the travelers_trips_history.
Attached the tables I have:
trips
travelers_trips_history
The query I did:
$query = "select traveler_trips_history.*, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
GROUP BY Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC
WHERE traveler_trips_history.Traveler_Username = $username";
I receive a error about the Group BY (check syntax), however, I am not sure the query is going to do what it should do.
Try this
SELECT traveler_trips_history.*
,COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history
INNER JOIN trips ON travelers_trips_history.Trip_Num = trips.Trip_Num
WHERE traveler_trips_history.Traveler_Username = $USERNAME
GROUP BY traveler_trips_history.travelers_trips_history
,traveler_trips_history.Username
,traveler_trips_history.Trip_Num
,traveler_trips_history.Trip_Type
,traveler_trips_history.Trip_Season
ORDER BY Trip_Geographic_occurrence DESC
You have 2 issues in your query:
1- You should have the where clause before the GroupBy Clause
2- If you GroupBy Col1, you can only select Col1 or use Aggregate Functions on another Columns (SUM, AVG, etc...)
You need to check the Rules for GroupBy and understand it better.
Edit after your comment:
$query = "select Trip_Geographic, COUNT(*) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
WHERE traveler_trips_history.Traveler_Username = $username
GROUP BY Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC";
Try like this
The problem is your where clause and group by columns.
SELECT tr.Trip_Geographic
,COUNT(hs.*) AS Trip_Geographic_occurrence
FROM traveler_trips_history hs
INNER JOIN trips tr ON hs.Trip_Num = tr.Trip_Num
WHERE hs.Username = $USERNAME
GROUP BY tr.Trip_Geographic
ORDER BY Trip_Geographic_occurrence DESC
Your problem is Haing WHERE clause after GROUP By and using columns that are not in GROUPED BY or AGGREGATE functions.
Try the following which has the username, trip_geographic and the no of trips.
select traveler_trips_history.Traveler_Username, traveler_trips_history.Trip_Geographic, COUNT(trips.Trip_Geographic) AS Trip_Geographic_occurrence
FROM traveler_trips_history INNER JOIN trips ON
travelers_trips_history.Trip_Num = trips.Trip_Num
GROUP BY Trip_Geographic, traveler_trips_history.Traveler_Username
having traveler_trips_history.Traveler_Username = $username
ORDER BY Trip_Geographic_occurrence DESC
In php and mysql I use a join query on several tables. Each table has the field name title. I want to get the value of title from each JOINed table, but when I retrieve each row of my result set with php, I only get the last value of title, This is my query.
SELECT UC.user_id,
UC.courses_id,
UC.semester_id,
UC.batch_id,
UC.department_id,
U.title,
U.firstname,
U.lastname,
B.title ,
CO.title,
SE.title,
DEP.title
FROM tbl_user_courses AS UC
INNER JOIN tbl_user AS U ON UC.user_id = U.id
INNER JOIN tbl_batch AS B ON UC.user_id = B.id
INNER JOIN tbl_courses AS CO ON UC.user_id = CO.id
INNER JOIN tbl_semester AS SE ON UC.user_id = SE.id
INNER JOIN tbl_departments AS DEP ON UC.user_id = DEP.id
where UC.trash=0
order by UC.user_id desc
Its php code
<?php
if($rec)
foreach( $rec as $value => $k){
?>
<?php echo $k['title'];
<?php echo $k['title'];?>
<?php echo $k['title'];?>
<?php echo $k['title'];?>
}
Now How can i get each table title its a field name.
You can give the fields an alias, by adding AS <alias> after the field.
SELECT UC.user_id,
UC.courses_id,
UC.semester_id,
UC.batch_id,
UC.department_id,
U.title as user_title,
U.firstname,
U.lastname,
B.title AS batch_title,
CO.title AS course_title,
SE.title AS semester_title,
DEP.title AS department_title
FROM tbl_user_courses AS UC
INNER JOIN tbl_user AS U ON UC.user_id = U.id
INNER JOIN tbl_batch AS B ON UC.user_id = B.id
INNER JOIN tbl_courses AS CO ON UC.user_id = CO.id
INNER JOIN tbl_semester AS SE ON UC.user_id = SE.id
INNER JOIN tbl_departments AS DEP ON UC.user_id = DEP.id
where UC.trash=0
order by UC.user_id desc
If you run this query, you can use the aliases instead of the field name, so use $k['department_title'] to get the name of the department.
I think that 'title' is a rather odd term to use for the name of department or course, but if they would all be named 'name' you would have the same issue again. :D
By the way, you could use a naming convention to reduce collisions like this. Just like you have department_id (and not just id) you could also use department_name or just department. Still, it's good to know about aliases, because you will need them sooner or later.
When you use fetch_assoc() functions in PHP to retrieve rows from your result set, if some of your columns have the same name you'll lose data. You have, as you know, a whole bunch of columns called title.
You want something like this, putting aliases on some of your result set columns so they don't all have the same name.
These aliases don't change the names of columns in your tables. They change the names of the columns in the results of your query only. When you say
SELECT title AS user_title
it fetches the column named title from the table, but then gives it the name user_title in the result set.
Try this:
SELECT UC.user_id, UC.courses_id, UC.semester_id, UC.batch_id, UC.department_id,
U.title AS user_title,
U.firstname, U.lastname,
B.title AS batch_title,
CO.title AS course_title,
SE.title AS semester_title,
DEP.title AS department_title
...
Then, in php, use code like this....
<?php echo $k['user_title'];
<?php echo $k['batch_title'];?>
<?php echo $k['course_title'];?>
<?php echo $k['semester_title'];?>
<?php echo $k['department_title'];?>
Alternatively, you can, if you're using PDO, fetch each row of your result set into a numbered rather than associative array.
$sth = $dbh->prepare("/*YOUR ORIGINAL QUERY8?") || die "prepare failed";
$sth->execute() || die "execute failed";
while ( $k = $sth->fetch( PDO::FETCH_NUM ) ) {
<?php echo 'batch title: ';echo $k[8];?>
<?php echo 'course title: ';echo $k[9];?>
/* etcetera */
}
This works because it fetches the columns of each row in your result set into a numerically indexed array ( 0 .. n) rather than an associative array.
You can also, in the obsolete mysql API, get the same effect with
while ($k = mysql_fetch_array($resultset, MYSQL_NUM) ) {
/* handle the row */
}
What's the correct syntax to achieve this using 1 query instead of 2?
$result = mysql_query(SELECT * FROM users);
while($row = mysql_fetch_array($result)){
$result = mysql_query(SELECT SUM(balance) FROM users_account WHERE uid=$row[id]);
}
You should inner join both tables and group by user table.
You can add more columns in SELECT clause, remember to add also same columns to GROUP BY clause to get a standard SQL statement.
$query = " SELECT u.uid, SUM(a.balance)
FROM users_account a
INNER JOIN users u
ON u.uid = a.uid
GROUP BY u.uid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
...
Arrange $query concatenating strings if needed.
This will return all records form user_account table with user info :-
SELECT SUM(ua.balance),u.*,ua.* FROM users_account ua
left join users u on ua.users_account=u.id
GROUP BY u.id
$result = mysql_query(SELECT a.*, b.SUM(balance) AS user_balance FROM users a, users_account b WHERE uid=$row[id]);
I need to alter my existing JOIN query below to also include the data from users.image correlating to the UserID of the post maker. Something like:
users.image WHERE users.UserID = posts.userid
I am not very good with join queries yet. How would I do this?
Existing Query:
$result = mysql_query("SELECT posts.* FROM listen JOIN posts ON posts.userid = listen.listenid WHERE listen.userid = '$user_id' ORDER BY DATE desc") or die(mysql_error());
Just add another JOIN clause:
SELECT posts.*
FROM listen
JOIN posts ON (posts.userid = listen.listenid)
JOIN users ON (users.UserID = posts.userid)
WHERE listen.userid = '$user_id'
ORDER BY DATE desc
You may need to change the JOIN to a specific join such as LEFT JOIN, depending on what you're after.
Btw, it is easier to see the query on multiple lines.
Edit: You'll probably want to add additional items that you are selecting with your fields, such as SELECT posts.*, users.*