I am unable to get 3 count fields from 3 different tables by using this SQL query below. Can someone help me out where I mistaken. The first count is assigning to another 2 fields. Means if I get 'total_scenarios' count as 10 the remaining 2 options(total_career_sketches, video_count) are taking same value 10.
$this->db->select('users.id,users.name,users.user_lname,users.email,
count(fc_scenarios.user_id) as total_scenarios, count(career_sketch.user_id)
as total_career_sketches, count(video_tracker.user_id) as video_count
,career_timeline.filled_modules');
$this->db->from('users');
$this->db->join('fc_scenarios','users.id = fc_scenarios.user_id AND
fc_scenarios.status = "A" AND fc_scenarios.type = "o"','left');
$this->db->join('career_sketch','users.id = career_sketch.user_id AND
career_sketch.status = "A" AND career_sketch.type = "o"','left');
$this->db->join('video_tracker','users.id = video_tracker.user_id','left');
$this->db->join('career_timeline','users.id =
career_timeline.user_id','left');
$this->db->where('users.inkwiry_user != ',1);
$this->db->where('users.status','A');
$this->db->group_by('users.id');
Thanks,
Sateesh
You may need to count distinct values for your joined tables, I guess due to one to many relation you are getting multiple rows repeated rows because of joins, I suggest you to use distinct inside your count function like
$this->db->select('users.id,users.name,users.user_lname,users.email,
count(distinct fc_scenarios.id) as total_scenarios,
count(distinct career_sketch.id) as total_career_sketches,
count(distinct video_tracker.id) as video_count,
career_timeline.filled_modules')
Also your query is invalid because group by clause has only one column o group rows but in select list your are trying to select other columns too which are not included in group by and neither aggregate
You can try with following query, it will work
$this->db->select('users.id,users.name,users.user_lname,users.email,
count(distinct fc_scenarios.id) as total_scenarios, count(distinct career_sketch.id)
as total_career_sketches, count(distinct video_tracker.id) as video_count
,career_timeline.filled_modules');
$this->db->from('users');
$this->db->join('fc_scenarios','users.id = fc_scenarios.user_id AND
fc_scenarios.status = "A" AND fc_scenarios.type = "o"','left');
$this->db->join('career_sketch','users.id = career_sketch.user_id AND
career_sketch.status = "A" AND career_sketch.type = "o"','left');
$this->db->join('video_tracker','users.id = video_tracker.user_id','left');
$this->db->join('career_timeline','users.id =
career_timeline.user_id','left');
$this->db->where('users.inkwiry_user != ',1);
$this->db->where('users.status','A');
$this->db->group_by('users.id');
Related
Hi everyone I am in a problem.
I have a table that contains the job requests, which is called: richieste
Another table that contains the appointments which is called: appuntamenti
I have to count how many times the id of a worker, in this case the 57 is present when there is a join between the table: richieste and appuntamenti.
nothing easier.
$q_count_appto_manager = $connessione->prepare("
SELECT count('ID_Richiesta')
FROM richieste
LEFT JOIN appuntamento
ON richieste.ID_Richiesta = appuntamento.appto_id_richiesta
WHERE operato_manager = ?
OR operato_manager_capo_a_manager = ?
OR team_manager = ?
OR team_manager_capo_a_team_manager = ?
AND appuntamento.appto_stato = 'NC'
");
$q_count_appto_manager->bind_param("iiii", $pro,$pro,$pro,$pro);
$q_count_appto_manager->execute();
$r_count_appto_manager = $q_count_appto_manager->get_result();
$rcam=mysqli_fetch_array($r_count_appto_manager);
?>
<?php
if ($rcam[0] == 0) {
echo $rcam[0];
} else {
echo $rcam[0];
}
now the problem begins, the worker with id: 57, can have more positions within the table: richieste, as you can read from the query, in the OR part.
and as you can see from the image
57 ID
so in this case the query will count every time the 57 is present in those positions, generating as output results: 4.
The problem is that I'm asking him to count 57 when he is in those positions, only when there is a join between the two tables, which as a true result should come out: 1
So it doesn't take the where condition into account as unique, but just counts how many times 57 exists in those positions.
How can I specify an attribute of uniqueness, limiting the query to count only when the 57 is in those positions and there is a join between the two tables?
AND has higher precedence than OR, so you need to use parentheses:
WHERE (operato_manager = ? OR operato_manager_capo_a_manager = ? OR
team_manager = ? OR team_manager_capo_a_team_manager = ?)
AND appuntamento.appto_stato = 'NC'
You might find it simpler to use IN with a single parameter:
WHERE appuntamento.appto_stato = 'NC' AND
? IN (operato_manager, operato_manager_capo_a_manager, team_manager, team_manager_capo_a_team_manager)
I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...
I need to obtain the sum of many values with the same key from a SQL Query.
For example...say I have 30 rows returned from a Query and they look like this.
1) (a:2), (b:4),(f:1), (h:3)
2) (c:2), (f:4),(t:1), (z:3)
3) (a:5), (b:2),(s:1), (z:3)
4) (d:2), (g:4),(s:1), (t:3)
and so on....
What I need to do is sum up all the "a" and all the "b" and all the "c" etc
And put all that into an array or object so I can access them for later processing.
$total = [(a:7),(b:6),(c:2),(d:2).....(z:6)];
Is there a way to do this all from SQL? Or do I have to sum all these records externally using PHP for example?
This is my SQL code to obtain the 30 records...
while($row = mysql_fetch_array($rs)) {
$queryActivity = "SELECT activity, count(activity) FROM users u, activities_users au, activities a WHERE ($row[zip] = u.zip AND u.id = au.user_id AND au.activity_id = a.id) GROUP BY a.activity";
$rs2 = mysql_query($queryActivity);
while($row2 = mysql_fetch_array($rs2)) {
echo "<tr><td>$row2[0]</td><td>";
echo "<tr><td>$row2[1]</td><td>";}
It returns all the activities and the sum of those activities for a certain zipcode. I just need to total all the sums up for each activity.
Is (a:2), (b:4)... is a row in the database?
You will need to use some sort of split, SUM, and GROUP BY's. It will be hard to help until we have more information.
So here is a quick query that will group by the first subset of the rows. You can do the same thing for every other subset. I don't know of a way to do what you want to do in pure mysql.
SELECT
SUBSTRING(activity, 1,2),
count(activity)
FROM users u, activities_users au, activities a
WHERE ($row[zip] = u.zip AND u.id = au.user_id AND au.activity_id = a.id)
GROUP BY SUBSTRING(activity, 1,2)
I am not sure I fully understand your requirement, but you can use the SUM() method in sql.
SELECT SUM(column_name) FROM table GROUP BY column_name
Add WITH ROLLUP to your query after GROUP BY clause:
SELECT activity, count(activity)
FROM users u, activities_users au, activities a
WHERE ($row[zip] = u.zip AND u.id = au.user_id AND au.activity_id = a.id)
GROUP BY a.activity WITH ROLLUP
It will add an extra row (null, totalsum) to the result set which you need to handle in PHP.
As alternative, you can calculate it with PHP inside your while loop:
$total[$row2[0]] = (empty($total[$row2[0]]) ? 0 : $total[$row2[0]]) + $row2[1]
Consider the following table
I need to return a list in descending order with the count of the member_nr's who is appearing the most frequent in the table where tournament = 'EPL' AND ROUND = '12'
EXAMPLE
The script should return the following results:
I thought about the problem and my logic for the problem reads like this
STEP1: GET member_nr one by one
$sql = "SELECT DISTINCT *
FROM winners
WHERE tournament='$tour' AND round='$round'";
LOOP(){ //get 1 member number
$mem_nr = ['mem_nr']; //assign mem_nr to variable
STEP2: GET the count(number of times) ^ABOVE^ member number appears in table
"$sql="SELECT *, count(member_nr) as nrWins
FROM winners
where member_nr ='$memNr' and tournament='$tournament' AND round='$round'";"
LOOP(){//get count
STEP 3: DISPLAY DATA
echo $row=['nrWins'] //Display Number Wins
echo $memNr
}//END LOOP
}//END LOOP
My Problem:
The above does not seem very efficient to me, im looking for the shortest most efficient way to return the count of member numbers in table above, any ideas / suggestions are welcomed
Try something like this:
SELECT *, COUNT(*) AS `wins`
FROM `winners`
WHERE `tournament` = '$tournament'
AND `round` = '$round'
GROUP BY `member_nr`
ORDER BY `wins` DESC
select tournament,round,member_nr,count(*)
from table
where tournament = 'EPL'
and round = 12
group by tournament,round,member_nr
order by count(*) desc
The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.
$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0"
The problem is that some electors will have more than one pledge in the voting_intentions table.
I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.
What is the simplest way of implementing that.
The rest of the code:
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) {
echo $row['ID'].','; }
}
You could use a sub-select with the MAX() function. Add the following into your WHERE clause.
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
Here is a SQLFiddle of the results.
So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here.
Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):
SELECT voting_intention.*
FROM voting_intention
INNER JOIN
(
SELECT elector, MAX(date) AS MaxDate
FROM voting_intention
GROUP BY elector
) groupedintention ON voting_intention.elector = groupedintention.elector
AND voting_intention.date = groupedintention .MaxDate
Question url: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?